var http = require('http'),
    fs = require('fs'),
    util = require('util'),
    proxy = require('request');


http.createServer(function (request, response) {
   //console.log("request.url = " + request.url);
   saveLog(request.method, request.url);
   proxy(('https://maps.googleapis.com' + request.url), function (error, res, body) {
        if (!error && response.statusCode == 200) {
          response.setHeader('Content-Type', res.headers['content-type']);
          response.end(body);
        } else {
          response.setHeader('Content-Type', 'text/html');
          response.end('error request');
        }
   });
}).listen(8088,  function(){
     console.log('proxy listen 8088.');
});

function saveLog(method, url) {
    fs.appendFileSync('./logs/proxy.log', util.format('[%s]\n%s %s\n\n', getFormatedTime(), method, url));
}
function log(msg){
    fs.appendFileSync('./logs/connection.log', util.format('[%s] - %s\n', getFormatedTime(), msg));
}
function getFormatedTime() {
    var dt = new Date();
    return dt.getFullYear() + '-' + formatNum(dt.getMonth() + 1, 2) + '-' + formatNum(dt.getDate(), 2) + ' ' + formatNum(dt.getHours(), 2) + ':' + formatNum(dt.getMinutes(), 2) + ':' + formatNum(dt.getSeconds(), 2) + '.' + formatNum(dt.getMilliseconds(), 3);
}

function formatNum(num, len) {
    return ('000' + num).slice(-len);
}